<template>
  <div class="main">
    <Top name1='商品管理' name2="添加商品"></Top>
    <el-card style="margin-top:40px;height: 800px;width: 1400px;">
        <el-alert
            title="添加商品信息"
            type="info"
            :closable="false"
            center
            show-icon>
        </el-alert>
        <el-steps :space="200" :active="activeId*1" style="margin-left:100px;margin-top: 15px;" :align-center="true" finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <el-form style=" margin-top:20px "  ref="goodsInfoForm" :model="goodsInfoForm" >
            <el-tabs tab-position="left" @tab-click="changeTab" :before-leave="qiehuan">
                <el-tab-pane label="基本信息" name="0" style="padding:0 0 0 20px">
                    <el-form-item label="商品名称" 
                        prop="goods_name"
                        :rules="[
                            { required: true, message: '请输入商品名称', trigger: 'blur' },
                        ]">
                        <el-input v-model="goodsInfoForm.goods_name" ></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" 
                        prop="goods_price"
                        :rules="[
                            { required: true, message: '请输入商品价格', trigger: 'blur' },
                        ]">
                        <el-input v-model="goodsInfoForm.goods_price" ></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量" 
                        prop="goods_weight"
                        :rules="[
                            { required: true, message: '请输入商品重量', trigger: 'blur' },
                        ]">
                        <el-input v-model="goodsInfoForm.goods_weight" ></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" 
                        prop="goods_name"
                        :rules="[
                            { required: true, message: '请输入商品数量', trigger: 'blur' },
                        ]">
                        <el-input v-model="goodsInfoForm.goods_number" ></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类"
                        prop="goods_cat"
                        :rules="[
                            { required: true, message: '请选择商品分类', trigger: 'blur' },
                        ]">
                          <el-cascader
                            v-model="goodsInfoForm.goods_cat"
                            ref="addTree"
                            :options="CateDate"
                            :clearable="true"
                            :props="{ label: 'cat_name',expandTrigger: 'hover',value:'cat_id'}"
                            @change="handleChange"
                        ></el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane name="1"  label="商品参数">
                    <el-form-item
                        :label="item.attr_name"
                        v-for="item in onlyFormData"
                        :key="item.attr_id"
                        >
                        <el-checkbox-group
                            v-model="item.attr_vals"
                            @change="handleCheckedAttrValsChange"
                        >
                            <el-checkbox
                            v-for="el in item.attr_vals"
                            :key="el"
                            :label="el"
                            border
                            >{{ el }}</el-checkbox
                            >
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane name="2"  label="商品属性">
                    <el-form-item
                        :label="item.attr_name"
                        v-for="item in manyFormData"
                        :key="item.attr_id"
                        >
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane name="3" label="商品图片">
                    <el-upload
                        class="upload-demo"
                        action="http://127.0.0.1:8888/api/private/v1/upload"
                        :on-success="picAdd"
                        :on-remove="picRem"
                        list-type="picture"
                        :headers="headers"
                        >
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            只能上传jpg/png文件，且不超过500KB
                        </div>
                        </el-upload>
                </el-tab-pane>
                <el-tab-pane name="4" label="商品内容">
                    <template>
                        <div style="border: 1px solid #ccc;">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editor"
                                :defaultConfig="toolbarConfig"
                                :mode="mode"
                            />
                            <Editor
                                style="height: 500px; overflow-y: hidden;"
                                v-model="goodsInfoForm.goods_introduce"
                                :defaultConfig="editorConfig"
                                :mode="mode"
                                @onCreated="onCreated"
                            />
                        </div>
                        <el-button type="success" @click="addGoods">添加商品</el-button>
                    </template>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>
  </div>
</template>
<script>
import Top from '../../components/top.vue'
import {getGoodsAjax} from '../../api/categories'
import {getParams} from '../../api/CateAttr'
import {setGoods} from '../../api/goods'
import { Editor, Toolbar } from '../../../node_modules/@wangeditor/editor-for-vue'
import _ from 'lodash'
  export default {
    components: {Top, Editor, Toolbar },
    data () {
      return {
        activeId:"0",
        goodsInfoForm:{
            goods_name:'',
            goods_cat:[],
            goods_price:0,
            goods_number:0,
            goods_weight:0,
            goods_introduce:'',
            pics:[],
            attrs:[],
        },        
        CateDate:[],
        value:[],
        flag:true,
        manyFormData:[],
        onlyFormData:[],
        headers:{'Authorization':window.sessionStorage.getItem('token')},
        editor: null,
            html: '',
            toolbarConfig: { },
            editorConfig: { placeholder: '请输入内容...' },
            mode: 'default', // or 'simple'

      };
    },
    async created() {
        const res = await getGoodsAjax()
        if(res.data.meta.status != 200){
            return this.$message.error("获取分类列表失败")
        }
        this.CateDate = res.data.data
    },
    mounted() {

    },
    methods: {
        handleChange(value){
            this.goodsInfoForm.goods_cat = value
        },
        // 切换前判断 不填商品名称 和 商品分类 不能跳转
        async qiehuan(activeName,oldActiveName){
            this.activeId = activeName
            if(oldActiveName == '0' && 
            this.goodsInfoForm.goods_name.length == 0 && 
            this.goodsInfoForm.goods_cat.length !=3){
                this.$message.error("请填写商品名称和商品分类");
                return false;
            }
        },
        // 点击到指定页面 加载相应的数据
        async changeTab(active){
            if(active.name == "2"){
                const res =  await getParams({
                    id: this.goodsInfoForm.goods_cat[this.goodsInfoForm.goods_cat.length-1],
                    sel:"many"
                })
                if(res.data.meta.status!=200){
                    return this.$message.error("获取参数失败")
                }
                this.manyFormData = res.data.data
            }
              if(active.name == '1'){
                const res =  await getParams({
                    id: this.goodsInfoForm.goods_cat[this.goodsInfoForm.goods_cat.length-1],
                    sel:"only"
                })
                if(res.data.meta.status!=200){
                    return this.$message.error("获取参数失败")
                }
                res.data.data.forEach(el => {
                    el.attr_vals = el.attr_vals == [] ? [] : el.attr_vals.split(',')
                });
                this.onlyFormData = res.data.data
            }
           
        },
        // 选项变化，form的数据随之变化
        handleCheckedAttrValsChange(){
            // console.log(this.manyFormData);
        },
        // // 图片上传成功的回调
        picAdd(res,file,addlist){
            var arr = []
            addlist.forEach(ele => {
                const obj = {
                    pic:ele.response.data.tmp_path
                }
                arr.push(obj)
            });
            this.goodsInfoForm.pics = arr;
        },
        // 删除图片
        picRem(rem,list){
            var arr = []
            list.forEach(ele => {
                const obj = {
                    pic:ele.response.data.tmp_path
                }
                arr.push(obj)
            });
            this.goodsInfoForm.pics = arr;
        },
        // 确认添加
        async addGoods(){ 
            if(this.goodsInfoForm.goods_name!=''&&this.goodsInfoForm.goods_cat.length==3&&this.goodsInfoForm.goods_price!=0
            &&this.goodsInfoForm.goods_number!=0&&this.goodsInfoForm.goods_weight!=0
            ){
                // 动态参数数组
                var manyarr = []
                this.manyFormData.forEach(e => {
                    manyarr.push({
                        attr_id:e.attr_id,
                        attr_vals:e.attr_vals
                    })
                });
                // 静态参数数组
                var onlyarr = []
                this.onlyFormData.forEach(e => {
                    onlyarr.push({
                        attr_id:e.attr_id,
                        attr_vals:e.attr_vals
                    })
                });
                // 克隆一个参数对象
                const newobj = _.cloneDeep(this.goodsInfoForm)
                // 把他的分类数组变成字符串
                newobj.goods_cat = newobj.goods_cat.join(',')
                // 把参数组成一个数组
                const arrs = [].concat.apply(manyarr,onlyarr)
                newobj.attrs = arrs

                // console.log(newobj);
                const res = await setGoods(newobj)
                if(res.data.meta.status != 201){
                    return this.$message.error('商品添加失败')
                }
               this.$message.success('添加成功')
               this.activeId = 5
               return this.$router.push('/goods')
            }else{
                return this.$message.error("信息填写不全，请查看信息是否正确")
            }
        },
        //
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
     
    },
    computed: {

    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
  }
</script>
<style lang='scss' scoped>
    .main{
        padding: 20px 40px;
    }
</style>